package com.pfc.others;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;

import android.content.Context;
import android.util.Log;
/*  * 
 * guarda lecturas con esta estructura:
 * nombre_lugar.txt
 * 
 * SSID_1 ,LEVEL_1 ,FREC_1 ;SSID_2 ,LEVEL_2 ,FREC_2 ;SSID_3 ,LEVEL_3 ,FREC_3 ...  (lectura 1)
 * SSID_1 ,LEVEL_1 ,FREC_1 ;SSID_2 ,LEVEL_2 ,FREC_2; SSID_3 ,LEVEL_3, FREC_3 ...  (lectura 2)
 * SSID_1 ,LEVEL_1 ,FREC_1 ;SSID_2 ,LEVEL_2 ,FREC_2 ;SSID_3 ,LEVEL_3 ,FREC_3 ...  (lectura 3)
 * ......
 */



public class FileManagement {

	private Context context;		// contexto de la aplicacion
	private String directory;		
	private static final String TAG = FileManagement.class.toString();	
	private static final String LOC_DEFAULT = "default";
	
	public FileManagement(Context c) {
		super();
		this.context = c;
		this.directory = this.context.getDir("locateme", Context.MODE_PRIVATE).getAbsolutePath();
		
	}
			
	public Lectura lineToElements(String linea){
		Lectura lista = new Lectura();
		linea = linea.replaceAll(" ", "");
		String[] s = linea.split(";");
		for (int i=0 ; i<s.length; i++){
			lista.add(stringToElement(s[i]));
		}
		return lista;
	}
	
	public Element stringToElement(String linea){
		Element e = new Element();		
		String[] s = linea.split(",");
		e.setBssid(s[0]);
		e.setSsid(s[1]);
		e.setLevel(Integer.parseInt(s[2]));
		e.setFrec(Integer.parseInt(s[3]));
		return e;
	}
	
	public ConjuntoLecturas readFile(String loc, String fileName){
		  File archivo = null;
	      FileReader fr = null;
	      BufferedReader br = null;
	      Lectura lectura = new Lectura();
	      ConjuntoLecturas listaLecturas = new ConjuntoLecturas(fileName.replace("_"+loc+"_PFC.txt", ""));
	 
	      try {
	         archivo = new File (this.directory+"/"+ fileName);
	         fr = new FileReader (archivo);
	         br = new BufferedReader(fr);
	         String linea="";
	         while((linea = br.readLine())!=null && !linea.equals("")){
	           lectura = lineToElements(linea);
	           listaLecturas.add(lectura);
	         }
	      }
	      catch(Exception ex){
	    	  Log.e(TAG, "Fallo en la lectura del archivo", ex);
	      }finally{
	         try{                    
	            if( null != fr ){   
	            	br.close();
	            	fr.close(); 
	            }
	            return listaLecturas;
	         }catch (Exception e2){ 
	            e2.printStackTrace();  
	         }
	      }return listaLecturas;
	}
	
	public void writeIntoFile(ConjuntoLecturas listaLecturas, String fileName){
		FileWriter fichero = null;
        PrintWriter pw = null;
        try{
            fichero = new FileWriter(this.directory+"/"+fileName, true);
            pw = new PrintWriter(fichero);
            for (int i=0 ; i<listaLecturas.size(); i++){
            	Lectura lectura = (Lectura)listaLecturas.get(i);
                pw.println(lectura.toString());
            }
        } catch (Exception ex) {
        	Log.e(TAG, "Fallo en la lectura del archivo", ex);
        } finally {
           try {
	           if (null != fichero){
	              fichero.close();
	           	  pw.close();
	           	}
           } catch (Exception e2) {
              e2.printStackTrace();
           }
        }
	}
	
	public String getPlaceFromNameFile(String nameFile){
		int first = nameFile.indexOf("_");
		String place = nameFile.substring(0, first);
		return place;
	}
	
	public String getLocationFromNameFile(String nameFile){
		int first = nameFile.indexOf("_");
		int sec = nameFile.indexOf("_", first+1);
		String locat = nameFile.substring(first+1, sec );
		return locat;
	}
	
	public String[] getAllFileList(){
		File dir = new File(this.directory);
		String[] ficheros_PFC = dir.list();
		return ficheros_PFC;
	}
	
	public ArrayList<String> getFileListFromLocation(String loc){
		// si getAllFileList = null es que no hay ningun fichero.
		System.out.println("Localizacion en fileListFromLocation: "+loc);
		String[] ficheros_PFC = this.getAllFileList();
		ArrayList<String> files = new ArrayList<String>();
		if (ficheros_PFC==null)
			return files;
		for(int i=0; i<ficheros_PFC.length; i++){
			String locat = getLocationFromNameFile(ficheros_PFC[i]);
			if (loc.equals(locat)){
				files.add(ficheros_PFC[i]);
			}
		}
		return files;
	}
	
	public void deleteFileFromLocation(String name){
		File f = new File(this.directory+"/"+name);
		f.delete();
	}
	
	public void deleteAllFilesFromLocation(String loc){
		ArrayList<String> files = getFileListFromLocation(loc);
		for (int i=0 ; i<files.size(); i++){
			File f = new File(this.directory+"/"+files.get(i));
			f.delete();
		}
	}
	
	public ArrayList<String> getLocationsListFromFiles(){
		String[] files = getAllFileList();
		ArrayList<String> locations = new ArrayList<String>();
		for (int i=0 ; i<files.length ; i++){
			String locat = getLocationFromNameFile(files[i]);
			if (!locations.contains(locat))
				locations.add(locat);
		}
		return locations;
	}
	

	public String getDefaultLocation(){
		ArrayList<String> locationList = getLocationsListFromFiles();
		if (locationList.isEmpty())
			return LOC_DEFAULT;
		else
			return locationList.get(0);
	}
}
